package com.yizhubao.app.activitys;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.yizhubao.app.R;
import com.yizhubao.app.activitys.release.ReleaseActivity;
import com.yizhubao.app.adapters.ReleaseImageAdapter;
import com.yizhubao.app.adapters.WelfareImageAdapter;
import com.yizhubao.app.base.BaseActivityToolBar;
import com.yizhubao.app.beans.RecordBean;
import com.yizhubao.app.beans.SelectImageBean;
import com.yizhubao.app.beans.WelfareBean;
import com.yizhubao.app.customviews.BottomDialog;
import com.yizhubao.app.events.LoginEvent;
import com.yizhubao.app.presenters.WelfarePresenter;
import com.yizhubao.app.utils.Constants;
import com.yizhubao.app.utils.GlideEngine;
import com.yizhubao.app.utils.Utils;
import com.yizhubao.app.views.WelfareView;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import h.framework.pacy.utils.ImageUtil;
import h.framework.pacy.utils.JsonUtil;
import h.framework.pacy.utils.LogUtil;
import h.framework.pacy.utils.PreferencesUtil;
import h.framework.pacy.utils.ScreenUtil;
import h.framework.pacy.utils.StringUtil;
import h.framework.pacy.utils.ToastUtil;
import h.framework.pacy.views.recyclerview.DividerDecoration;

/**
 * 创建人: PACY
 * 创建时间: 6/6/21 10:25 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: 公益通道
 */
public class WelfareActivity extends BaseActivityToolBar implements WelfareView {

    @BindView(R.id.selectJob_tv)
    TextView selectJob_tv;


    //身份证正面
    @BindView(R.id.idCard_z)
    ImageView idCard_z;
    @BindView(R.id.delete_z)
    ImageView delete_z;
    private WelfareBean.UrlListBean cardZ;
    @BindView(R.id.bofangz_iv)
    ImageView bofangz_iv;

    //身份证反面
    @BindView(R.id.idCard_f)
    ImageView idCard_f;
    @BindView(R.id.delete_f)
    ImageView delete_f;
    private WelfareBean.UrlListBean cardF;
    @BindView(R.id.bofangf_iv)
    ImageView bofangf_iv;

    //图片选择
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.image_rv)
    RecyclerView image_rv;
    WelfareImageAdapter adapter;
    GridLayoutManager layoutManager;


    WelfarePresenter presenter;
    WelfareBean bean;

    private OSS oss;

    @Override
    protected int setContentLayout() {
        return R.layout.activity_welfare;
    }

    @Override
    protected void initView() {
        setTitleOnLeftIcon(R.drawable.icon_back, "");
        initImagePicker();
    }

    @Override
    protected void initData() {
        initOss();
        bean = new WelfareBean();
        List<WelfareBean.UrlListBean> urlListBean = new ArrayList<>();
        bean.setUrlList(urlListBean);
        bean.getUrlList().add(new WelfareBean.UrlListBean(true));
        adapter.setNewData(bean.getUrlList());
        presenter = new WelfarePresenter();
        presenter.attachView(this);

    }

    /**
     * 发送提交请求
     */
    private void sendRequest() {
        if (selectJob_tv.getText().toString().equals("请选择")) {
            ToastUtil.showShort("请选择岗位");
            return;
        }
        if (cardZ == null || cardF == null) {
            ToastUtil.showShort("请上传身份证照片");
            return;
        }

        if (adapter.getItemCount() < 2) {
            ToastUtil.showShort("请上传岗位证明");
            return;
        }

        if (bean.getUrlList().get(bean.getUrlList().size() - 1).isAdd()) {
            bean.getUrlList().remove(bean.getUrlList().size() - 1);
        }
        bean.setUserId(Long.parseLong(Utils.getUserId()));
        bean.getUrlList().add(cardZ);
        bean.getUrlList().add(cardF);

        LogUtil.i(JsonUtil.objectToJson(bean));

        Map<String, Object> map = new HashMap<>();
        map = JsonUtil.jsonToMap(JsonUtil.objectToJson(bean));
        showLoading();
        presenter.sendRequest(map);
    }

    @OnClick(value = {R.id.selectJob_tv, R.id.idCard_add_z, R.id.delete_z, R.id.idCard_z, R.id.idCard_add_f, R.id.delete_f, R.id.idCard_f, R.id.submit_tv})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.selectJob_tv:
                BottomDialog.DialogBuilder(WelfareActivity.this).title("温馨提示")
                        .message(" ①依据国家相关规定，目前仅支持下列岗位可以免费使用遗嘱宝。②如果提交虚假材料，发现后，会直接影响到您的个人征信。③有任何问题，请联系平台客服。")
                        .completeText("知道了").completeCallBack(() -> {
                    showJobDialog();
                }).show();
                break;

            case R.id.idCard_add_z:
                selectCardImage(true);
                break;

            case R.id.delete_z:
                cardZ = null;
                idCard_z.setVisibility(View.GONE);
                delete_z.setVisibility(View.GONE);
                bofangz_iv.setVisibility(View.GONE);
                break;
            case R.id.idCard_z:
                Bundle bundle = new Bundle();
                bundle.putString("path", cardZ.getUrl());
                if(cardZ.getType()==1){
                    startActivity(WelfareActivity.this, PhotoViewActivity.class, bundle);
                }else{
                    startActivity(WelfareActivity.this,VideoActivity.class,bundle);
                }

                break;

            case R.id.idCard_add_f:
                selectCardImage(false);
                break;

            case R.id.delete_f:
                cardF = null;
                idCard_f.setVisibility(View.GONE);
                delete_f.setVisibility(View.GONE);
                bofangf_iv.setVisibility(View.GONE);
                break;
            case R.id.idCard_f:
                Bundle bundle2 = new Bundle();
                bundle2.putString("path", cardF.getUrl());
                if(cardZ.getType()==1){
                    startActivity(WelfareActivity.this, PhotoViewActivity.class, bundle2);
                }else{
                    startActivity(WelfareActivity.this,VideoActivity.class,bundle2);
                }

                break;

            case R.id.submit_tv:
                sendRequest();
                break;
        }
    }


    /**
     * 初始化阿里云OSS
     */
    private void initOss() {
        //云OSS初始化配置
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.accessKeyId, Constants.accessKeySecret);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), Constants.endpoint, credentialProvider, conf);
    }

    /**
     * 设置图片选择的UI
     */
    private void setImageUI() {
        if (bean.getUrlList().size() > 9) {
            bean.getUrlList().remove(bean.getUrlList().size() - 1);
        } else {
            if (!bean.getUrlList().get(bean.getUrlList().size() - 1).isAdd()) {
                bean.getUrlList().add(bean.getUrlList().size(), new WelfareBean.UrlListBean(true));
            }
        }
        adapter.setNewData(bean.getUrlList());
    }

    /**
     * 递归的方式上传图片
     *
     * @param urls
     */
    private void ossUpload(List<SelectImageBean> urls, int orginType, boolean isZ) {
        if (urls.size() <= 0) {
            // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThead做对应逻辑
            runOnUiThread(() -> {
                LogUtil.i("全部上传完成");
                dismissDialog();
                if (orginType == 2) {
                    setImageUI();
                } else {
                    setCardUI(isZ);
                }

            });
            return;
        }

        final String temp = Utils.getUUID(urls.get(0).getType());

        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(Constants.testBucket, Constants.uploadObject + temp, urls.get(0).getImageUrl());

        // 异步上传时可以设置进度回调
        put.setProgressCallback((request, currentSize, totalSize) -> LogUtil.i("currentSize: " + currentSize + " totalSize: " + totalSize));

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtil.i(result.getETag());
                LogUtil.i(result.getRequestId() + "-----" + result.getResponseHeader().toString());
                LogUtil.i("上传成功---");
                WelfareBean.UrlListBean dto = new WelfareBean.UrlListBean();
                dto.setType(urls.get(0).getType());
                dto.setUrl(Constants.ossImagePath + temp);
                dto.setOrginType(orginType);
                if (orginType == 2) {
                    bean.getUrlList().add(bean.getUrlList().size() - 1, dto);
                } else {

                    if (isZ) {
                        cardZ = dto;
                    } else {
                        cardF = dto;
                    }

                }
                urls.remove(0);
                ossUpload(urls, orginType, isZ);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                    LogUtil.e("ErrorCode=" + serviceException.getErrorCode() + "\nRawMessage=" + serviceException.getRawMessage());
                }
                runOnUiThread(() -> {
                });
            }
        });
    }

    /**
     * 选择身份证图片
     */
    private void selectCardImage(boolean isZ) {
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                .setFileProviderAuthority("com.yizhubao.app.fileprovider")//参数说明：见下方`FileProvider的配置`
                .setCount(1)//参数说明：最大可选数，默认1
                .setVideo(true)
                .setPuzzleMenu(false)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        LogUtil.i("size==" + photos.size());
                        List<SelectImageBean> beans = new ArrayList<>();
                        if (isZ) {
                            if (photos.get(0).type.equals("image/jpeg")||photos.get(0).type.equals("image/png")) {
                                beans.add(new SelectImageBean(photos.get(0).path, false, 1));
                            } else {
                                beans.add(new SelectImageBean(photos.get(0).path, false, 2));
                            }
                        } else {
                            if (photos.get(0).type.equals("image/jpeg")) {
                                beans.add(new SelectImageBean(photos.get(0).path, false, 1));
                            } else {
                                beans.add(new SelectImageBean(photos.get(0).path, false, 2));
                            }
                        }
                        uploadImage(beans, 1, isZ);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }


    /**
     * 选择岗位
     */
    private void showJobDialog() {

        List<String> jobs = new ArrayList<>();
        jobs.add("烈士家属");
        jobs.add("科研人员");
        jobs.add("军人/警察/消防 ...");
        jobs.add("医生/护士 ...");
        jobs.add("有资格证的老师");
        jobs.add("城市环卫工人");


        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            selectJob_tv.setText(jobs.get(options1));
            selectJob_tv.setTextColor(getResources().getColor(R.color.font_color));
            LogUtil.i(options1+1+"");
            bean.setType(options1+1);
        }).setSubmitColor(getResources()
                .getColor(R.color.btn_color_green))
                .setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.hintColor))
                .setTitleBgColor(Color.WHITE)
                .setContentTextSize(14)
                .setLineSpacingMultiplier(3f)
                .build();
        pvOptions.setPicker(jobs);
        pvOptions.show();
    }

    /**
     * 初始化图片选择列表
     */
    private void initImagePicker() {
        adapter = new WelfareImageAdapter();
        image_rv.setAdapter(adapter);
        layoutManager = new GridLayoutManager(WelfareActivity.this, 3);
        image_rv.setLayoutManager(layoutManager);
        //添加分割线
        DividerDecoration decoration = new DividerDecoration(getResources().getColor(R.color.transparent), ScreenUtil.dp2px(10));
        image_rv.addItemDecoration(decoration);

        adapter.setOnItemChildClickListener((ad, view, position) -> {
            if (view.getId() == R.id.delete_iv) {
                adapter.remove(position);
                if (!adapter.getItem(adapter.getItemCount() - 1).isAdd()) {
                    adapter.addData(adapter.getItemCount(), new WelfareBean.UrlListBean(true));
                }
            } else if (view.getId() == R.id.select_lin) {
                selectImage();
            } else if (view.getId() == R.id.image_rel) {
                if(adapter.getItem(position).getType()==1){
                    Bundle bundle=new Bundle();
                    bundle.putString("path",adapter.getItem(position).getUrl());
                    startActivity(WelfareActivity.this, PhotoViewActivity.class,bundle);
                }else{
                    Bundle bundle=new Bundle();
                    bundle.putString("path",adapter.getItem(position).getUrl());
                    startActivity(WelfareActivity.this, VideoActivity.class,bundle);
                }
            }
        });
    }

    /**
     * 请求保存
     */
    private void uploadImage(List<SelectImageBean> urls, int orginType, boolean isZ) {
        showLoading("请稍候");
        ossUpload(urls, orginType, isZ);
    }


    private void setCardUI(boolean isZ) {
        if (isZ) {
            ImageUtil.loadImage(cardZ.getUrl(), idCard_z);
            idCard_z.setVisibility(View.VISIBLE);
            delete_z.setVisibility(View.VISIBLE);
            if (cardZ.getType() == 1) {
                bofangz_iv.setVisibility(View.GONE);
            } else {
                bofangz_iv.setVisibility(View.VISIBLE);
            }
        } else {
            ImageUtil.loadImage(cardF.getUrl(), idCard_f);
            idCard_f.setVisibility(View.VISIBLE);
            delete_f.setVisibility(View.VISIBLE);
            if (cardF.getType() == 1) {
                bofangf_iv.setVisibility(View.GONE);
            } else {
                bofangf_iv.setVisibility(View.VISIBLE);
            }
        }

    }

    /**
     * 选择图片
     */
    private void selectImage() {
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                .setFileProviderAuthority("com.yizhubao.app.fileprovider")//参数说明：见下方`FileProvider的配置`
                .setCount(10-adapter.getItemCount())//参数说明：最大可选数，默认1
                .setPuzzleMenu(false)
                .setVideo(true)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        LogUtil.i("size==" + photos.size());
                        List<SelectImageBean> urls = new ArrayList<>();
                        for (Photo p : photos) {
                            if (p.type.equals("image/jpeg")||p.type.equals("image/png")) {
                                urls.add(new SelectImageBean(p.path, false, 1));
                            } else {
                                urls.add(new SelectImageBean(p.path, false, 2));
                            }
                        }
                        uploadImage(urls, 2, false);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Override
    public void onSaveSuccess(boolean success) {
        PreferencesUtil.put(Constants.HAS_SPECIAL,true);
        EventBus.getDefault().post(new LoginEvent());
        startActivity(WelfareActivity.this, WelfareSuccessActivity.class);
        finish();
    }
}